package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.component.UMengPushComponent;
import com.lebang.entity.LbbDict;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.TaskRewards;
import com.lebang.entity.TaskRewardsRecord;
import com.lebang.entity.member.LbbMember;
import com.lebang.example.LbbDictExample;
import com.lebang.example.TaskRewardsExample;
import com.lebang.mapper.*;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.buss.MemberTradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.lebang.controller.api.member.MemberApi.C_MEMBER_DATE;
import static com.lebang.controller.api.member.MemberApi.MEMBER_DATE;

/**
 * @Author: hwq
 * @Date: 2019/7/24 15:02
 * @Version 1.0
 */
@Service
public class MemberNewTaskService {
    @Autowired
    private RankingService rankingService;
    @Autowired
    private UMengPushComponent pushComponent;
    @Autowired
    private RedisClient redisClient;
    //每日必赚
    public static final Integer MRBZ = 8888;
    //基础任务
    private static final Integer BASE = 2;
    private static final Integer NEWHAND_TASK = 9999;
    //试玩任务
    private static final Integer TEST = 4;
    // 闲玩任务
    private static final Integer XIAN_WAN = 5;
    //傲天任务
    private static final Integer AO_TIAN = 6;
    //截图任务
    private static final Integer COMMON = 8;
    // 多游任务
    private static final Integer DUO_YOU = 9;
    // 91淘金任务
    private static final Integer TAO_JIN = 10;
    // pc蛋蛋任务
    private static final Integer PC_EGG = 11;
    // 聚享玩任务
    private static final Integer JU_XIANG_WAN = 12;
    // 91穿山甲看视频
    private static final Integer CSJ = 13;
    //小程序赚钱
    private static final Integer XCX = 14;
    //新闻赚
    private static final Integer XWZ = 15;
    //笑话赚
    private static final Integer XHZ = 16;
    //鱼玩盒子
    private static final Integer YW_hZ = 6000;
    //蛋蛋赚
    private static final Integer DD_Z = 6003;
    @Autowired
    private LbbDictMapper dictMapper;

    @Autowired
    private MemberTradeService memberTradeService;
    @Resource
    private TaskRewardsRecordMapper recordMapper;
    @Resource
    private TaskRewardsMapper rewardsMapper;
    @Autowired
    private LbbMemberMapper memberMapper;
    @Autowired
    private LbbMemberTradeMapper lbbMemberTradeMapper;




    public TaskRewardsRecord getRecordByMemberIdAndRewardsId(String memberId, Integer id) {
        return recordMapper.getRecordByMemberIdAndRewardsId(memberId, id);
    }

    public TaskRewardsRecord getRecordByMemberIdAndRecordId(String memberId, Integer id) {
        return recordMapper.getRecordByMemberIdAndRecordId(memberId, id);
    }

    public void pullRecord(TaskRewardsRecord record, RequestHeaders request) {
        record.setStatus(1);
        record.setModifyTime(new Date());
        recordMapper.updateByPrimaryKeySelective(record);
        memberTradeService.addMoney(record.getMemberId(), record.getMoney(),
                record.getMsg(), record.getMsg(), "", request, "",
                new MoneyCategory(Whether.NO, TaskCategory.NEW_HAND));
        pushComponent.sendNoRead("奖励通知", record.getMsg(), record.getMemberId());
        //新手任务只计入周榜
        rankingService.memberAddScore1(record.getMemberId(), record.getMoney());
    }

    public void pushRecord(TaskCategory category, String memberId) {
        if (memberMapper.getMemberByMemberId(memberId).getCreateTime().before(MEMBER_DATE)) {
            return;
        }

        switch (category) {

            case TASK_NEW_HAND:
                addRecord(9999, memberId);
                break;
            case AoTian:
                addRecord(AO_TIAN, memberId);
                break;
            case XianWan:
                addRecord(XIAN_WAN, memberId);
                break;
            case Empty:
                addRecord(TEST, memberId);
                break;
            case LEXIANG:
                addRecord(DUO_YOU, memberId);
                break;
            case PCDANDAN:
                addRecord(PC_EGG, memberId);
                break;
            case JUXIANGWAN:
                addRecord(JU_XIANG_WAN, memberId);
                break;
            case TAOJIN:
                addRecord(TAO_JIN, memberId);
                break;
            case CHUANGSHANJIA:
                addRecord(CSJ, memberId);
                break;
            case MDGG:
                addRecord(XCX, memberId);
                break;
            case NEWS_EARN:
                addRecord(XWZ, memberId);
                break;
            case JOKE_EARN:
                addRecord(XHZ, memberId);
                break;
            case YW_HZ:
                addRecord(YW_hZ, memberId);
                break;
            case DANDAN_ZHUAN:
                addRecord(DD_Z, memberId);
                break;
            default:
                break;
        }
    }

    public void addRecord(Integer i, String memberId) {
        Integer id = 1;
//        if (id == 1 || id > 4) {
//            return;
//        }
        TaskRewards rewards = rewardsMapper.checkRecord(id, i);
        if (rewards == null) {
            return;
        }
        if (rewards.getHasDeleted().equals(1)) {
            return;
        }
        Integer status = recordMapper.checkRecord(rewards.getId(), memberId);

        if (status == 0 /*&& !checkTime(id - 1, memberId)*/) {
            TaskRewardsRecord record = new TaskRewardsRecord();
            record.setCreateBy("newhand");
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMemberId(memberId);
            record.setRewardsId(rewards.getId());
            record.setIsTask(Whether.NO.getDbIndex());
            record.setMoney(rewards.getMoney());
            record.setStatus(0);
            record.setMsg(rewards.getMsg());
            record.setParentRerwordsId(rewards.getParentId());
            recordMapper.insertSelective(record);
        }

    }
    public List<TaskRewards> getRewardListByParentId(Integer status, String brand) {
        TaskRewardsExample example = new TaskRewardsExample();
        example.createCriteria()
                .andParentIdEqualTo(status)
                .andHasDeletedEqualTo(0)
                .andBrandNotLike("%" + brand + "%");
        example.setOrderByClause("sort");
        return rewardsMapper.selectByExample(example);
    }
    public int phase(RequestHeaders requsetHeader, String memberId, Integer id, String brand) {
        TaskRewards taskRewards = rewardsMapper.selectByPrimaryKey(id);
        if (taskRewards.getHasDeleted().equals(1)) {
            return 0;
        }
        Integer status = recordMapper.checkRecord(taskRewards.getId(), memberId);
        if (status > 0) {
            return -1;
        }
        TaskRewardsExample example = new TaskRewardsExample();
        example.createCriteria()
                .andParentIdEqualTo(id)
                .andHasDeletedEqualTo(0)
                .andBrandNotLike("%" + brand + "%");
        Long rewardsCount = rewardsMapper.countByExample(example);
        Long memberCount = recordMapper.memberCount(id, memberId);
        if (memberCount >= rewardsCount) {
            TaskRewardsRecord record = new TaskRewardsRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMemberId(memberId);
            record.setRewardsId(id);
            record.setIsTask(Whether.YES.getDbIndex());
            record.setMoney(taskRewards.getMoney());
            record.setStatus(1);
            record.setMsg(taskRewards.getMsg());
            record.setParentRerwordsId(id);
            recordMapper.insertSelective(record);
            pullRecord(record, requsetHeader);
            return 1;
        } else {
            return 0;
        }
    }

    public int base(TaskRewards rewards, String memberId) {
        Integer status = recordMapper.checkRecord(rewards.getId(), memberId);
        if (status == 0) {
            TaskRewardsRecord record = new TaskRewardsRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMemberId(memberId);
            record.setRewardsId(rewards.getId());
            record.setIsTask(0);
            record.setMoney(rewards.getMoney());
            record.setStatus(0);
            record.setMsg(rewards.getMsg());
            record.setParentRerwordsId(rewards.getParentId());
            recordMapper.insertSelective(record);
            return 1;
        }
        return 0;
    }

    public TaskRewards selectById(Integer id) {
        return rewardsMapper.selectByPrimaryKey(id);
    }

    /**
     * 判断上一阶段完成是否已经24小时了
     *
     * @param id
     * @return
     */
    public boolean checkTime(Integer id, String memberId) {
        if (id == 1) {
            return false;
        }
        TaskRewardsRecord record = recordMapper.selectByMemberIdAndRewId(id, memberId);
        Date date = record.getCreateTime();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, 1);
        date = c.getTime();
        Date date1 = new Date();

        return date.after(date1);
    }

    public List<TaskRewards> selectByExample(TaskRewardsExample example) {
        return rewardsMapper.selectByExample(example);
    }

    public Long countByExample(TaskRewardsExample example) {
        return rewardsMapper.countByExample(example);
    }

    public int updateReworads(TaskRewards rewards) {
        return rewardsMapper.updateByPrimaryKeySelective(rewards);
    }

    /**
     * 获取提现奖励列表的接口
     *
     * @param memberId 用户ID
     * @return
     */
    public List<LbbDict> selectRecordListByMemberId(String memberId) {
        LbbDictExample dictExample = new LbbDictExample();
        dictExample.createCriteria().andHasDeletedEqualTo(Booleans.False.name()).andKeynameEqualTo("cash");
        Integer checktrade = lbbMemberTradeMapper.selectTradeByMemberId(memberId);
        LbbMember member = memberMapper.getMemberByMemberId(memberId);
        if (member == null) {
            return new ArrayList<>();
        }
        //判断是否是老用户直接不展示这个列表
        if (checktrade > 3 || (member.getCreateTime().before(MEMBER_DATE) && !"cash".equals(member.getPersonId()))) {
            //
            return new ArrayList<>();
        } else {
            List<LbbDict> dicts = dictMapper.selectByExample(dictExample);
            dicts.forEach(vo -> {
                TaskRewardsRecord re = recordMapper.selectByCash(memberId, vo.getKeyvalue());
                if (re == null) {
                    vo.setKeyname("-1");
                } else {
                    vo.setKeyname(re.getStatus().toString());
                    vo.setId(re.getId().longValue());
                }
            });

            return dicts;
        }
    }

    public Map newMemberInfo() {

        Map map = new HashMap();
        String str = redisClient.get("newMemberInfo:newMemberInfo:newMemberInfo");
        if (str != null) {
            return JSON.parseObject(str);
        }
        //获取该阶段全部任务
        List<TaskRewards> rewards = this.getRewardListByParentId(1, "meizu");
        List<TaskRewards> no_rewards = this.getRewardListByParentId(2, "meizu");
        rewards.forEach(vo -> {
            if ("新手红包".equals(vo.getTitle())) {
                vo.setSort(0);
            } else {
                vo.setSort(-2);
            }

        });
        no_rewards.forEach(vo -> vo.setSort(-2));
        //判断是否完成了
        //下一阶段任务展示
        TaskRewards memberRewards = this.selectById(1);
        map.put("memberRewards", memberRewards);
        map.put("rewards", rewards);
        map.put("no_rewards", no_rewards);
        redisClient.setex("newMemberInfo:newMemberInfo:newMemberInfo", JSON.toJSONString(map), 86400);
        return map;
    }

    public int insert(TaskRewards rewards) {
        rewards.setCreateTime(new Date());
        rewards.setHasDeleted(1);
        rewards.setModifyTime(new Date());
        return rewardsMapper.insertSelective(rewards);
    }

    /**
     * 每日必赚次数
     * @param success
     * @param memberId
     */
    public void addMrbz(int success, String memberId) {
        if (memberMapper.getMemberByMemberId(memberId).getCreateTime().before(C_MEMBER_DATE)) {
            return;
        }
        TaskRewards rewards =rewardsMapper.selectByCategory(MRBZ,success,memberId);
        if(rewards==null){
            return;
        }
        Integer status = recordMapper.checkRecord(rewards.getId(), memberId);
        if (status == 0) {
            TaskRewardsRecord record = new TaskRewardsRecord();
            record.setCreateBy("newhand");
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMemberId(memberId);
            record.setRewardsId(rewards.getId());
            record.setIsTask(Whether.NO.getDbIndex());
            record.setMoney(rewards.getMoney());
            record.setStatus(0);
            record.setMsg(rewards.getMsg());
            record.setParentRerwordsId(rewards.getParentId());
            recordMapper.insertSelective(record);
        }
    }

    public TaskRewards selectByCategory(Integer category) {
        return rewardsMapper.selectVoByCategory(category);
    }
}
